use crate::error::{TauriResult, CommandResponse};
use crate::types::{SystemInfo, MemoryInfo, CpuInfo, DiskInfo, WorkspaceValidation, ValidationIssue, IssueSeverity};
use tauri::command;
use std::path::Path;

/// 问候命令（示例）
#[command]
pub fn greet(name: &str) -> TauriResult<CommandResponse<String>> {
    let message = format!("Hello, {}! Welcome to CodeGraph-RT!", name);
    log::info!("Greeting: {}", message);
    Ok(CommandResponse::success(message))
}

/// 获取系统信息
#[command]
pub async fn get_system_info() -> TauriResult<CommandResponse<SystemInfo>> {
    log::debug!("Getting system information");
    
    let system_info = SystemInfo {
        os: std::env::consts::OS.to_string(),
        arch: std::env::consts::ARCH.to_string(),
        version: get_os_version(),
        memory: get_memory_info(),
        cpu: get_cpu_info(),
        disk: get_disk_info(),
    };
    
    log::debug!("System info collected: {} {}", system_info.os, system_info.arch);
    Ok(CommandResponse::success(system_info))
}

/// 验证工作区
#[command]
pub async fn validate_workspace(path: String) -> TauriResult<CommandResponse<WorkspaceValidation>> {
    log::info!("Validating workspace: {}", path);
    
    let workspace_path = Path::new(&path);
    let mut issues = Vec::new();
    let mut suggestions = Vec::new();
    
    // 检查路径是否存在
    if !workspace_path.exists() {
        issues.push(ValidationIssue {
            severity: IssueSeverity::Error,
            message: "工作区路径不存在".to_string(),
            path: Some(path.clone()),
            line: None,
            column: None,
        });
    } else if !workspace_path.is_dir() {
        issues.push(ValidationIssue {
            severity: IssueSeverity::Error,
            message: "指定路径不是目录".to_string(),
            path: Some(path.clone()),
            line: None,
            column: None,
        });
    } else {
        // 检查是否为空目录
        if let Ok(entries) = std::fs::read_dir(workspace_path) {
            let entry_count = entries.count();
            if entry_count == 0 {
                issues.push(ValidationIssue {
                    severity: IssueSeverity::Warning,
                    message: "工作区目录为空".to_string(),
                    path: Some(path.clone()),
                    line: None,
                    column: None,
                });
                suggestions.push("考虑添加一些源代码文件来开始分析".to_string());
            }
        }
        
        // 检查常见的项目文件
        let project_files = [
            "package.json", "Cargo.toml", "pom.xml", "build.gradle", 
            "requirements.txt", "go.mod", "composer.json"
        ];
        
        let mut found_project_file = false;
        for file in &project_files {
            if workspace_path.join(file).exists() {
                found_project_file = true;
                break;
            }
        }
        
        if !found_project_file {
            issues.push(ValidationIssue {
                severity: IssueSeverity::Info,
                message: "未找到常见的项目配置文件".to_string(),
                path: Some(path.clone()),
                line: None,
                column: None,
            });
            suggestions.push("添加项目配置文件（如 package.json, Cargo.toml 等）可以提供更好的分析结果".to_string());
        }
        
        // 检查是否有源代码文件
        if let Ok(entries) = std::fs::read_dir(workspace_path) {
            let mut has_source_files = false;
            for entry in entries.flatten() {
                if let Some(extension) = entry.path().extension() {
                    let ext = extension.to_string_lossy().to_lowercase();
                    if matches!(ext.as_str(), "rs" | "py" | "js" | "ts" | "java" | "cpp" | "c" | "go") {
                        has_source_files = true;
                        break;
                    }
                }
            }
            
            if !has_source_files {
                issues.push(ValidationIssue {
                    severity: IssueSeverity::Warning,
                    message: "未找到支持的源代码文件".to_string(),
                    path: Some(path.clone()),
                    line: None,
                    column: None,
                });
                suggestions.push("确保工作区包含支持的编程语言文件（Rust, Python, JavaScript, TypeScript, Java, C/C++, Go）".to_string());
            }
        }
        
        // 检查权限
        if let Ok(metadata) = std::fs::metadata(workspace_path) {
            if metadata.permissions().readonly() {
                issues.push(ValidationIssue {
                    severity: IssueSeverity::Warning,
                    message: "工作区目录为只读".to_string(),
                    path: Some(path.clone()),
                    line: None,
                    column: None,
                });
                suggestions.push("确保对工作区目录有写入权限以保存分析结果".to_string());
            }
        }
    }
    
    let is_valid = !issues.iter().any(|issue| matches!(issue.severity, IssueSeverity::Error));
    
    let validation = WorkspaceValidation {
        is_valid,
        issues,
        suggestions,
    };
    
    log::info!("Workspace validation completed: valid={}, issues={}", 
               validation.is_valid, validation.issues.len());
    
    Ok(CommandResponse::success(validation))
}

/// 获取操作系统版本
fn get_os_version() -> String {
    #[cfg(windows)]
    {
        // Windows 版本检测
        "Windows".to_string()
    }
    
    #[cfg(target_os = "macos")]
    {
        // macOS 版本检测
        "macOS".to_string()
    }
    
    #[cfg(target_os = "linux")]
    {
        // Linux 版本检测
        std::fs::read_to_string("/etc/os-release")
            .unwrap_or_default()
            .lines()
            .find(|line| line.starts_with("PRETTY_NAME="))
            .and_then(|line| line.split('=').nth(1))
            .map(|name| name.trim_matches('"').to_string())
            .unwrap_or_else(|| "Linux".to_string())
    }
    
    #[cfg(not(any(windows, target_os = "macos", target_os = "linux")))]
    {
        "Unknown".to_string()
    }
}

/// 获取内存信息
fn get_memory_info() -> MemoryInfo {
    // 简化的内存信息获取
    // 在实际应用中，可以使用 sysinfo crate 获取更准确的信息
    MemoryInfo {
        total: 8 * 1024 * 1024 * 1024, // 8GB 示例
        available: 4 * 1024 * 1024 * 1024, // 4GB 示例
        used: 4 * 1024 * 1024 * 1024, // 4GB 示例
    }
}

/// 获取 CPU 信息
fn get_cpu_info() -> CpuInfo {
    // 简化的 CPU 信息获取
    CpuInfo {
        cores: num_cpus::get(),
        frequency: 2400, // 2.4GHz 示例
        usage: 0.0, // 0% 示例
    }
}

/// 获取磁盘信息
fn get_disk_info() -> DiskInfo {
    // 简化的磁盘信息获取
    DiskInfo {
        total: 500 * 1024 * 1024 * 1024, // 500GB 示例
        available: 200 * 1024 * 1024 * 1024, // 200GB 示例
        used: 300 * 1024 * 1024 * 1024, // 300GB 示例
    }
}
